import json
import hashlib
import re
import time
import random
import string
from urllib.parse import quote
import requests

ApiKey = "你的ApiKey"
ApiUrl = "https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat"
header = {'Content-Type': 'application/json;charset=UTF-8'}
# 腾讯闲聊
ApiId = '你的ApiId'
AppKey = '你的AppKey'
# 如意机器人
RuyiUrl = "http://api.ruyi.ai/v1/message"
Ruyikey = "你的Key"
# 思知机器人
SiZhiUrl = "https://api.ownthink.com/bot"
SiZhiID = "你的ID"


# 图灵的要钱，整不起
def TuLinChat(context):
    ChatData = {
        "reqType": 0,
        "perception": {
            "inputText": {
                "text": context
            },
            "selfInfo": {
                "location": {
                    "city": "你的省份",
                    "province": "你的城市",
                    "street": "你的地区"
                }
            }
        },
        "userInfo": {
            "apiKey": ApiKey,
            "userId": "kratos"
        }
    }
    res = requests.post(ApiUrl, json=ChatData, headers=header)
    resDict = json.loads(res.text)
    print(resDict)


# 海知如意机器人
def RuyiChat(context):
    ChatData = {
        "q": context,
        "app_key": Ruyikey,
        "user_id": "Kratos",
        # "reset_session": True,
        "context": {
            "location": {
                "latitude": "经度",
                "longitude": "纬度"
            }
        }
    }
    res = requests.post(RuyiUrl, json=ChatData, headers=header)
    resDict = json.loads(res.text)
    if resDict["msg"] == "ok":
        text = resDict["result"]["intents"][0]["outputs"][0]["property"]["text"]
        text = text.replace("\\n", "\n")
        return text
    # print(resDict)


# 思知机器人
def SiZhiChat(context):
    ChatData = {
        "spoken": context,
        "appid": SiZhiID,
        "userid": "Kratos"
    }
    res = requests.post(SiZhiUrl, json=ChatData, headers=header)
    resDict = json.loads(res.text)
    print(resDict)


# 腾讯AI智能闲聊
def AIQQChat(context):
    context = context.encode('utf-8')
    payload = GetParam(context)
    res = requests.post(ApiUrl, data=payload)
    res = res.json()
    if res["ret"]:
        print(res)
        return res["msg"]
    return res["data"]["answer"]


def Url2Md5(src):
    m = hashlib.md5(src.encode('UTF-8'))
    # 将得到的MD5值所有字符转换成大写
    return m.hexdigest().upper()


def GetParam(context):
    t = time.time()
    ts = str(int(t))
    nonce_str = ''.join(random.sample(string.ascii_letters + string.digits, 10))
    params = {'app_id': ApiId,
              'question': context,
              'time_stamp': ts,
              'nonce_str': nonce_str,
              'session': '10000'
              }
    AppSign = ''
    for key in sorted(params):
        AppSign += '{}={}&'.format(key, quote(params[key], safe=''))
    AppSign += 'app_key={}'.format(AppKey)
    sign = Url2Md5(AppSign)
    params['sign'] = sign
    return params


if __name__ == '__main__':
    # print(SiZhiChat("我叫小火车"))
    # print(AIQQChat("我叫小火车"))
    print(RuyiChat("现在几点啦"))